package com.jinyang.jetpackdemo.activity

import android.content.*
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.jinyang.jetpackdemo.NetworkUtils
import com.jinyang.jetpackdemo.R
import kotlinx.android.synthetic.main.activity_broad_cast.*
import androidx.localbroadcastmanager.content.LocalBroadcastManager


class BroadCastActivity : AppCompatActivity() {
    private lateinit var localReceiver111: LocalReceiver
    private lateinit var localBroadcastManager: LocalBroadcastManager
    private lateinit var netWorkChangeReceiver: NetWorkChangeReceiver
    private lateinit var netWorkChangeReceiver2222: NetWorkChangeReceiver22222

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_broad_cast)
        //注册广播
        val intentFilter = IntentFilter()
        intentFilter.addAction(ACTION_CONNECTIVITY_CHANGE)
        intentFilter.addAction(ACTION_MY)
        netWorkChangeReceiver = NetWorkChangeReceiver()
        intentFilter.priority = -1000// priority 必须是整数，默认是0    范围是[-1000, 1000]
//        registerReceiver(netWorkChangeReceiver, intentFilter)
        netWorkChangeReceiver2222 = NetWorkChangeReceiver22222()
        registerReceiver(netWorkChangeReceiver2222, IntentFilter())
        registerReceiver(netWorkChangeReceiver2222, IntentFilter())
        registerReceiver(netWorkChangeReceiver2222, IntentFilter())
        registerReceiver(netWorkChangeReceiver2222, IntentFilter())
        registerReceiver(netWorkChangeReceiver2222, IntentFilter())
        unregisterReceiver(netWorkChangeReceiver2222)
        registerReceiver(netWorkChangeReceiver2222, IntentFilter())
        unregisterReceiver(netWorkChangeReceiver2222)
        registerReceiver(netWorkChangeReceiver2222, IntentFilter())
        unregisterReceiver(netWorkChangeReceiver2222)
        registerReceiver(netWorkChangeReceiver2222, IntentFilter())
        btn_sendBroadcast_ACTION_MY.setOnClickListener {
            val intent = Intent(ACTION_MY)
            if (Build.VERSION.SDK_INT >= 26) {
//                intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)//加上这句话，可以解决在android8.0系统以上2个module之间发送广播接收不到的问题}
                intent.setPackage(packageName)
            }
            sendBroadcast(intent)

//            sendImplicitBroadcast(this, intent)
        }
        btn_sendBroadcastSticky_ACTION_MY.setOnClickListener {
            val intent = Intent(ACTION_MY)
            sendStickyBroadcast(intent)
            btn_sendBroadcast_ACTION_MY.postDelayed({
                registerReceiver(netWorkChangeReceiver, intentFilter)
            }, 3000)
        }
        btn_sendOrderedBroadcast_ACTION_MY.setOnClickListener {
            //发送有序广播
            val intent = Intent(ACTION_MY)
            intent.setPackage(packageName)
            sendOrderedBroadcast(intent, null)//第二个参数是一个与权限相关的字符串，这里传 null 就行了
        }

        localBroadcastManager = LocalBroadcastManager.getInstance(this)
        //本地广播注册
        val intentFilter1 = IntentFilter(ACTION_MY)
        intentFilter1.priority = -1000
        localReceiver111 = LocalReceiver()
        localBroadcastManager.registerReceiver(LocalReceiver(), intentFilter1)
        val intentFilter2 = IntentFilter(ACTION_MY)
        intentFilter2.priority = 1000
        localBroadcastManager.registerReceiver(LocalReceiver222(), intentFilter2)
        val intentFilter3 = IntentFilter(ACTION_MY)
        localBroadcastManager.registerReceiver(LocalReceiver333(), intentFilter3)
        btn_sendLocalBroadcast_ACTION_MY.setOnClickListener {
            //发送本地广播
            localBroadcastManager.sendBroadcast(Intent(ACTION_MY));
        }
    }

    /**
     * Background execution not allowed: receiving Intent 问题解决
    1.如果是在一个进程中的app组件之间的通信，可以改成使用：LocalBroadcastManager
    2.如果是在多进程中的app组件之间的通信，可以改成显示广播（explicit broadcasts）
    3.如果你是在接受系统发的隐式广播，请保证你的sdk在25及以下，直到我们找到更好的解决放法。
    4.如果你是在编写发送隐式广播，你可以通过直到接收器并且发送定向的显示广播来打破这个限制。方法如下：
     */
    private fun sendImplicitBroadcast(context: Context, intent: Intent) {
        val pm: PackageManager = context.packageManager
        val matches: List<ResolveInfo> = pm.queryBroadcastReceivers(intent, 0)
        for (resolveInfo in matches) {
            val explicit = Intent(intent)
            val cn = ComponentName(
                resolveInfo.activityInfo.applicationInfo.packageName,
                resolveInfo.activityInfo.name
            )
            explicit.component = cn
            context.sendBroadcast(explicit)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //销毁广播
        unregisterReceiver(netWorkChangeReceiver)
        localBroadcastManager.unregisterReceiver(localReceiver111)
    }


}

val ACTION_CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE"
val ACTION_MY = "com.jinyang.jetpackdemo.ACTION_MY"

class LocalReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        log("LocalReceiver.onReceive: ${intent?.action}")
    }
}

class LocalReceiver222 : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        log("LocalReceiver222.onReceive: ${intent?.action}————${this.hashCode()}")
        if (intent?.action == ACTION_MY) {
//            abortBroadcast()//本地广播不能调用abortBroadcast，报错Call while result is not pending
        }
    }
}

class LocalReceiver333 : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        log("LocalReceiver333.onReceive: ${intent?.action}")
    }
}

class NetWorkChangeReceiver22222 : BroadcastReceiver() {
    init {
        log("NetWorkChangeReceiver222222:————${this}")
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        log("NetWorkChangeReceiver.onReceive: ${intent?.action}————${this}")
    }
}

class NetWorkChangeReceiver : BroadcastReceiver() {
    init {
        log("NetWorkChangeReceiver:————${this}")
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        log("NetWorkChangeReceiver.onReceive: ${intent?.action}————${this}")
        if (intent?.action == ACTION_MY) {
            abortBroadcast()//表示这条广播截断，后面的广播接收器无法再接受到这条广播
        }
        if (intent?.action == ACTION_CONNECTIVITY_CHANGE) {
            log("onReceive: 网络发生变化")
            val netType = NetworkUtils.getNetType()
            log("netType:$netType")
            if (NetworkUtils.isNetworkAvailable()) {
                log("onReceive: 网络连接成功")
            } else {
                log("onReceive: 网络连接失败")
            }
        }

    }
}

class BootBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        log("BootBroadcastReceiver.onReceive: ${intent?.action}————${this}")
        if ("android.intent.action.BOOT_COMPLETED" == intent?.action) {
            context?.startActivity(Intent(context, KotlinsActivity::class.java).addFlags(FLAG_ACTIVITY_NEW_TASK))
//            val service = Intent(context, MyServiceForeground::class.java)
//            context?.startService(service)
        }
    }
}
